package com.zxu.test.ipc.client;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.Observable;
import androidx.lifecycle.ViewModelProviders;

import com.zxu.test.base.BaseFragment;
import com.zxu.test.header.CommonTipHeaderViewModel;
import com.zxu.test.ipc.Book;
import com.zxu.test.ipc.server.BookManager;
import com.zxu.test.ipc.server.RemoteService;
import com.zxu.test.ipc.server.Stub;
import com.zxu.test.studyapp.databinding.ActivityClientBinding;
import com.zxu.test.util.Event;

import java.util.List;


public class ClientFragment extends BaseFragment {

    private CommonTipHeaderViewModel mHeader;
    private ActivityClientBinding mBinding;
    private ClientViewModel mViewModel;
    private BookManager bookManager;
    private boolean isConnection = false;

    public ClientFragment() { }

    public static ClientFragment getInstance() {
        return new ClientFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = ActivityClientBinding.inflate(inflater, container, false);
        mViewModel = ViewModelProviders.of(getActivity()).get(ClientViewModel.class);
        mBinding.setViewModel(mViewModel);
        mHeader = ViewModelProviders.of(this).get(CommonTipHeaderViewModel.class);
        mHeader.setTitle("ipc");
        mHeader.setTip("取消");
        mBinding.setHeader(mHeader);
        return  mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setupListener();
    }

    private void setupListener() {
        mHeader.getBackCommand().observe(getViewLifecycleOwner(), this::close);
        mHeader.getTipEvent().observe(getViewLifecycleOwner(), this::historyList);
        mViewModel.btnEvent.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (!isConnection) {
                    attemptToBindService();
                    return;
                }
                if (bookManager == null)
                    return;
                try {
                    Book book = new Book();
                    book.setPrice(101);
                    book.setName("编码");
                    bookManager.addBook(book);
                    Log.i("ClientActivity    s", "size()"+bookManager.getBooks().size());
                    for(int i=0; i < bookManager.getBooks().size() ; i++){
                        Log.i("ClientActivity    s", "for()"+bookManager.getBooks().get(i).toString());
                    }
                    Log.i("ClientActivity    s", bookManager.getBooks().toString());

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void attemptToBindService() {
        Intent intent = new Intent(getContext(), RemoteService.class);
        intent.setAction("com.zxu.test.ipc");
        getActivity().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }



    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isConnection = true;
            bookManager = Stub.asInterface(service);
            if (bookManager != null) {
                try {
                    List<Book> books = bookManager.getBooks();
                    Log.i("ClientActivity    f", "size()"+bookManager.getBooks().size());
                    for(int i=0; i < bookManager.getBooks().size() ; i++){
                        Log.i("ClientActivity    f", "for()"+bookManager.getBooks().get(i).toString());
                    }
                    Log.i("ClientActivity    f", books.toString());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isConnection = false;
        }

    };

    @Override
    public void onStart() {
        super.onStart();
        if (!isConnection) {
            attemptToBindService();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (isConnection) {
            getActivity().unbindService(serviceConnection);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void close(Event<Object> objectEvent) {
        if(objectEvent.getContentIfNotHandled() != null) {
            getActivity().finish();
        }
    }
    private void historyList(Event<Object> objectEvent) {
        if(objectEvent.getContentIfNotHandled() != null) {
            getActivity().finish();
        }
    }
}
